package com.xyh.concurrency.example.concueerncyAqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * AQS 中的限流组件就是限定流量的组件
 */
@Slf4j
public class SemaphoreDemo1 {
    private final static int cuont = 20;

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(3);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < cuont; i++) {
            int cotdowcount = i;
            executorService.execute(() -> {
                try {
                    //获取当前时间段允许获取的并发连接数,如果获取的并发运行时间不够长的时间就进行线程丢弃
                    if (semaphore.tryAcquire()) {
                        test(cotdowcount);
                        //释放许可
                        semaphore.release();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            });
        }
        log.info("kaishi");
        executorService.shutdown();
    }

    public static void test(int cuont) throws InterruptedException {
        Thread.sleep(100);
        log.info("{}", cuont);

    }
}
